package geektime.spring.springbuks.config;

import com.alibaba.druid.pool.DruidDataSource;
import geektime.spring.springbuks.model.DruidProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "geektime.spring.springbuks.dao.db1", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DB1DataSourceConfig {

    @Bean("db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1") //读取application.yml中的配置参数映射成为一个对象
    @Primary
    public DataSource getDataSource(DruidProperties druidProperties){

//        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
//        return druidProperties.dataSource(dataSource);
        return null;

    }

    @Bean("db1SqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);;
        return bean.getObject();
    }

    @Bean("db1SqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "db1TransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("db1DataSource") DataSource ds) {
        return new DataSourceTransactionManager(ds);
    }
}